package com.gy.controller.assistant;


import com.gy.controller.assistant.dto.ChatMessageDTO;
import com.gy.controller.assistant.dto.ConversationSummaryDTO;
import com.gy.controller.common.UserHolder;
import com.gy.entity.User;
import com.gy.result.Result;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.service.AiServices;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.v3.oas.annotations.Operation;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/xiaoning")
public class XiaoningController {

    @Autowired
    private XiaoNingAgent xiaoningAgent;

    @Autowired
    private MongoChatMemoryStore chatMemoryStore;

    @Operation(summary = "流式对话")
    @PostMapping(
            value = "/chat",
            produces = MediaType.TEXT_EVENT_STREAM_VALUE
    )
    public Flux<ServerSentEvent<Result<String>>> chat(@RequestBody ChatForm chatForm) {
        try {
            Long userId = UserHolder.getUser().getUserId();

            if (chatForm.getMemoryId() == null) {
                return Flux.just(
                        ServerSentEvent.<Result<String>>builder()
                                .data(Result.error("memoryId不能为空"))
                                .build()
                );
            }

            String globalMemoryId = userId + ":" + chatForm.getMemoryId();

            // 获取 AI 流式响应
            Flux<String> aiStream = xiaoningAgent.chat(globalMemoryId, chatForm.getUserMessage())
                    .doOnNext(content -> System.out.println("AI原始片段：" + content));

            //用 ServerSentEvent 包装 Result，WebFlux 自动生成 SSE 格式
            return aiStream
                    .map(content -> ServerSentEvent.<Result<String>>builder()
                            .data(Result.success(content))  // Result.success 包装正常数据
                            .build()
                    )
                    .onErrorResume(e -> Flux.just(
                            ServerSentEvent.<Result<String>>builder()
                                    .data(Result.error("对话处理失败：" + e.getMessage()))  // Result.error 包装错误
                                    .build()
                    ))
                    .concatWith(Mono.just(
                            ServerSentEvent.<Result<String>>builder()
                                    .data(Result.success("stream_end"))  // Result 包装结束标记
                                    .build()
                    ));

        } catch (Exception e) {
            return Flux.just(
                    ServerSentEvent.<Result<String>>builder()
                            .data(Result.error("对话处理失败：" + e.getMessage()))
                            .build()
            );
        }
    }


    /**
     * 查询当前用户的所有会话列表（概览）
     */
    @Operation(summary = "查询用户的所有会话")
    @GetMapping("/conversations")
    public Result<List<ConversationSummaryDTO>> getUserConversations() {
        try {
            Long userId = UserHolder.getUser().getUserId();
            List<ConversationSummaryDTO> conversations = chatMemoryStore.getUserConversations(userId);
            return Result.success(conversations);
        } catch (Exception e) {
            return Result.error("查询会话列表失败：" + e.getMessage());
        }
    }

    /**
     * 查询某个会话的详细聊天记录
     * @param memoryId 会话ID（用户内的局部ID，非globalMemoryId）
     */
    @Operation(summary = "查询会话的详细聊天记录")
    @GetMapping("/conversations/{memoryId}")
    public Result<List<ChatMessageDTO>> getConversationDetails(@PathVariable Long memoryId) {
        try {
            Long userId = UserHolder.getUser().getUserId();
            String globalMemoryId = userId + ":" + memoryId; // 拼接全局ID

            List<ChatMessageDTO> messages = chatMemoryStore.getConversationDetails(globalMemoryId);
            return Result.success(messages);
        } catch (Exception e) {
            return Result.error("查询会话详情失败：" + e.getMessage());
        }
    }

    /**
     * 删除某个会话
     * @param memoryId 会话ID（用户内的局部ID，非globalMemoryId）
     */
    @Operation(summary = "删除会话")
    @DeleteMapping("/conversations/{memoryId}")
    public Result<Void> deleteConversation(@PathVariable Long memoryId) {
        try {
            Long userId = UserHolder.getUser().getUserId();
            String globalMemoryId = userId + ":" + memoryId; // 拼接全局ID

            // 调用存储层删除方法
            chatMemoryStore.deleteMessages(globalMemoryId);
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除会话失败：" + e.getMessage());
        }
    }
}
